﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Profile;
using System.Text;

using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;

namespace WebSite.admin.order
{
    public partial class selectGoodsList : BaseAdmin
    {
       readonly  DALGoods theGoods = new DALGoods();
       readonly DALBrand theBrand = new DALBrand();
       readonly DALtbTempCar theTbCar = new DALtbTempCar();
       readonly DALCard theCard = new DALCard();
       DB_Card oCard;
        tbGoods oGoods;
       tbTempCar oCar;


    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!base.IsPostBack)
        {
         
            btnSaveRefresh.OnClientClick = Grid1.GetNoSelectionAlertInTopReference("没有选中项！");
            this.Display("0", "|--");
            this.BindGrid();
        }
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.BindGrid();
    }

    protected void Grid1_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
    {
        Grid1.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    string GetSqlWhere
    {
        get
        {
            StringBuilder strWhere = new StringBuilder();
            strWhere.AppendLine(" isnull(isSale,0) = 1 ");
            if (!string.IsNullOrEmpty(Request.QueryString["typeids"]))
            {
                string sTypeIds = Request.QueryString["typeids"];
                strWhere.AppendFormat(" and T.goodsId in (select goodsId from tbGoodsCardType where cardTypeId in ({0}))"
                                       , sTypeIds.Substring(1, sTypeIds.Length - 1)).Replace("-",",");
            }
            if (Request.QueryString["cardcode"] != null)
            {
                oCard = theCard.GetModelByCardCode(Request.QueryString["cardcode"]);
            }
            if (oCard.UseWay == 0)//通用
            {
                strWhere.AppendFormat(" and isnull(allowAllCard,0) = 1 ");
            }
            if (this.ddlGoodsType.SelectedItem.Value != "-1")
            {
                strWhere.AppendFormat(" and typeId = {0}", this.ddlGoodsType.SelectedItem.Value);
            }
            if (this.txtPointsFrom.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ((isnull(isRush,0) = 0 and changePoints >= {0}) or (isnull(isRush,0) = 1 and getDate() between rushTimeFrom  and rushTimeTo and rushPoints >={0} ))    ", this.txtPointsFrom.Text.Trim());
            }
            if (this.txtPointsFrom.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ((isnull(isRush,0) = 0 and changePoints <= {0}) or (isnull(isRush,0) = 1 and getDate() between rushTimeFrom  and rushTimeTo and rushPoints <={0} ))    ", this.txtPointsFrom.Text.Trim());
            }
            if (this.txtKeywords.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and (goodsName like '{0}' or goodsCode like '{0}')", this.txtKeywords.Text.Trim());
            }
            return strWhere.ToString();
        }
    }


    protected void Grid1_Sort(object sender, ExtAspNet.GridSortEventArgs e)
    {
        DataTable table =  theGoods.GetListByPage(GetSqlWhere, string.Format("{0} {1}", e.SortField, e.SortDirection), Grid1.PageIndex, Grid1.PageSize).Tables[0];
        Grid1.DataSource = table;
        Grid1.DataBind();
        ViewState["sort"] = e.SortField;
        ViewState["dir"] = e.SortDirection;
    }
    private void BindGrid()
    {   // 1.设置总项数
        Grid1.RecordCount = theGoods.GetRecordCount(GetSqlWhere.Replace("T.",""));
        string strOrderBy = string.Format("{0} {1} "
                                           , ViewState["sort"] == null ? null : ViewState["sort"].ToString()
                                           , ViewState["dir"] == null ? null : ViewState["dir"].ToString());
        if (strOrderBy.Length < 13)
        {
            strOrderBy = "goodsId desc ";
        }
        DataTable table = theGoods.GetListByPage(GetSqlWhere, strOrderBy, Grid1.PageIndex, Grid1.PageSize).Tables[0];

        Grid1.DataSource = table;
        Grid1.DataBind();
        Grid1.SelectedRowIndexArray = new int[] { };

    }

    private void Display(string parentid, string space)
    {
        string sql = "Select * From tbGoodsType Where parentId =" + parentid + " Order By typeOrder";
        DataTable table = new DataTable();
        table = SQLAccess.GreatDs(sql).Tables[0];
        if (table.Rows.Count > 0)
        {
            foreach (DataRow row in table.Rows)
            {
                this.ddlGoodsType.Items.Add(new ExtAspNet.ListItem(space + "" + row["typeName"].ToString() + "", "" + row["typeId"].ToString() + ""));
                this.Display(row["typeId"].ToString(), "|-" + space);
            }
        }
        if (ddlGoodsType.Items[0].Value != "-1")
        {
            this.ddlGoodsType.Items.Insert(0, new ExtAspNet.ListItem("请选择...", "-1"));
            this.ddlGoodsType.SelectedValue = this.ddlGoodsType.Items[0].Value;
        }
    }



    protected void btnSaveRefresh_Click(object sender, EventArgs e)
    {
        int selectedCount = this.Grid1.SelectedRowIndexArray.Length;
        StringBuilder sbProIds = new StringBuilder();
        for (int i = 0; i < selectedCount; i++)
        {
            int rowIndex = this.Grid1.SelectedRowIndexArray[i];

            oGoods = theGoods.GetModel(int.Parse(this.Grid1.DataKeys[rowIndex][0].ToString()));
            oCar = new tbTempCar();
            oCar.OrderCode = Int64.Parse( Request.QueryString["code"]);
            oCar.goodsCount = 1;
            oCar.GoodsPoints = int.Parse(this.Grid1.DataKeys[rowIndex][2].ToString());
            oCar.GoodsId = oGoods.goodsId;
            oCar.UpdateDate = DateTime.Now;
            oCar.Conents = string.Empty;
            oCar.ModelTypeId = int.Parse(this.Grid1.DataKeys[rowIndex][1].ToString());
            theTbCar.Add(oCar); 
        }
        ExtAspNet.PageContext.RegisterStartupScript(ExtAspNet.ActiveWindow.GetHidePostBackReference());
    }
    }
}